package  main.tools;

import java.io.*;

/**
 * @Description:
 * @Author: MenChao
 * @Date: 2018/12/10 11:11
 */
public class FileTools {



    public static Boolean writeFile(String filePath,String fileName,InputStream stream)  {
        if (stream == null) {
            return false;
        }
        FileOutputStream os = null;
        String fileFullPath =  filePath +  "/" + fileName;
        try {
            File file = new File(fileFullPath);
            if(file.exists()){
                file.deleteOnExit();
            }
            os = new FileOutputStream(file);
            byte[] bb = new byte[1024];
            int ch;
            while ((ch = stream.read(bb)) > -1) {
                os.write(bb, 0, ch);
            }
            os.close();
            stream.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return true;
    }

    public static void writeFileWithByte(String filePath,String fileName,byte [] data){
        try {
            String fileFullPath =  filePath +  "/" + fileName;
            File file = new File(fileFullPath);
            if(file.exists()){
                file.deleteOnExit();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data,0,data.length);
            fos.flush();
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    /***
     * 创建文件夹
     * @param path
     */
    public static   void createFloder(String path) throws  IOException{
        File rootDir = new File(path);
        //判断上传文件的保存目录是否存在
        if (!rootDir.exists() && !rootDir.isDirectory()) {
            //创建目录
            rootDir.mkdirs();
        }
    }


    public static  String getFileFullPath(String path,String fileName){
        return   path +  "/" + fileName;
    }

    /***
     * 获取文件名
     * @param path
     * @return
     */
    public static   String getFileName(String path){
        String fName = path.trim();
        String fileName = fName.substring(fName.lastIndexOf("/")+1);
        return fileName;
    }


    /**
     * 得到文件后缀名  如 test.png 取 png
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1) {
            return "";
        } else {
            return fileName.substring(point + 1, length);
        }
    }

    public static String getNamePart(String fileName) {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1) {
            return "";
        }else{
            return fileName.substring(0, point);
        }
    }




}
